import { TransformOptions } from '@babel/core'
import { isArray, isString, once } from 'lodash-es'

export const babelOptionsToJson = (options: TransformOptions) => {
  const {
    auxiliaryCommentAfter,
    auxiliaryCommentBefore,
    babelrc,
    babelrcRoots,
    browserslistConfigFile,
    browserslistEnv,
    caller,
    comments,
    compact,
    configFile,
    env,
    envName,
    generatorOpts,
    minified,
    moduleId,
    moduleIds,
    moduleRoot,
    parserOpts,
    plugins,
    presets,
    retainLines
  } = options

  return JSON.stringify([
    auxiliaryCommentAfter,
    auxiliaryCommentBefore,
    babelrc,
    babelrcRoots,
    browserslistConfigFile,
    browserslistEnv,
    caller,
    comments,
    compact,
    configFile,
    env,
    envName,
    generatorOpts,
    minified,
    moduleId,
    moduleIds,
    moduleRoot,
    parserOpts,
    plugins,
    presets,
    retainLines
  ])
}

export const babelConfigItemToPluginItem = (item: any) => {
  if (!item || isArray(item) || isString(item) || typeof item !== 'object') return item
  if ('manipulateOptions' in item || 'pre' in item || 'visitor' in item || 'post' in item || 'inherits' in item)
    return item

  const file = item.file
  const options = item.options

  if (file && typeof file === 'object') {
    const { resolved } = file
    if (typeof resolved === 'string') {
      return [resolved, options]
    }
  }

  return item
}
